<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015-5-28
 * Time: 15:46
 */

namespace zhtfrontend\controllers;

use common\components\extenders\AjaxObject;
use common\components\helpers\Fun;
use common\models\datas\CardAttr;
use common\models\datas\CardBatch;
use common\models\datas\CardReSend;
use common\models\datas\CardSend;
use common\models\datas\IsuserInfo;
use doumiaoduo\buildform\BuildForm;
use yii\data\Pagination;
use yii\helpers\Json;
use yii\web\NotFoundHttpException;
use yii\web\Response;
use yii\helpers\ArrayHelper;
use zhtfrontend\models\datas\Orders;

class CardsendController extends \zhtfrontend\components\bases\BaseController
{
    public function actionIndex()
    {
//        if (\Yii::$app->request->isAjax) {
//            \Yii::$app->response->format = Response::FORMAT_JSON;
//            if (\Yii::$app->request->post('param') != null) $param = Json::decode(\Yii::$app->request->post('param'));

            $pageSize = isset($param['pageSize']) ? $param['pageSize'] : 12;
            $data = CardSend::find()->where(['site_id' => Fun::getSiteId(),'parent_id'=>0])->orderBy('created_at DESC');
            if (isset(\Yii::$app->user->identity) && \Yii::$app->user->identity->role == 'business_director') {
                $iids = IsuserInfo::find()->select('id')->where(['response_man' => \Yii::$app->user->id])->column();
                $data->andWhere(['salesman_id' => $iids]);
            }
            $pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => $pageSize]);
            isset($param['page']) ? $pages->page = $param['page'] - 1 : 0;
            $model = $data->offset($pages->offset)->limit($pages->limit)->all();
//            $ajax_object = new AjaxObject();
            $array = Fun::asArray($model, ['site_name', 'salesman_name', 'admin_name', 'activationcount', 'batch_name', 'zhtfrontend_operate']);
//            $ajax_object->pages = $pages;
//            return $ajax_object;

        return $this->render('index',['data'=>$array,'pages'=>$pages]);
    }

    public function actionCreate()
    {
        $this->layout = false;
        $model = new CardSend();
        $card_batch = CardBatch::find()->where(['status' => 1, 'site_id' => Fun::getSiteId(), 'sendtype' => 0])->all();
        $isuserinfo = IsuserInfo::find()->indexBy('id')->where(['status' => 1, 'site_id' => Fun::getSiteId(), 'parent_id' => 0, 'operation_type' => ['all', 'card']])->asArray()->all();
        $batchs = ArrayHelper::map($card_batch, 'id', 'title');
        foreach ($batchs as $k => $v) {
            $count = CardAttr::find()->where(['batch_id' => $k, 'salesman_id' => 0])->count();
            if ($count > 0) {
                $batchs[$k] = $v . "(剩{$count}张)";
            } else {
                unset($batchs[$k]);
            }
        }
        $form = new BuildForm('@app/components/forms/sendForm.php');
        $form->loadModel(['send' => $model]);
        $form->setItems('send', 'batch_id', $batchs);
        $insert_arr = [];
        if (!empty($isuserinfo)) {
            foreach ($isuserinfo as $k => $v) {
                $str = !empty($v['name']) ? $v['name'] . '-' : '';
                $str .= !empty($v['contact']) ? $v['contact'] . '-' : '';
                $str .= $v['mobile'];
                $insert_arr[$k] = $str;
            }
        }
        $form->setData('send', 'salesman_id', 'data', $insert_arr);
        if ($form->loadData(\Yii::$app->request->post()) && $form->validate()) {
            $model->user_id = \Yii::$app->user->id;
            $model->number = $model->card_end - $model->card_start + 1;
            $model->site_id = Fun::getSiteId();
            CardAttr::updateAll(['salesman_id' => $model->salesman_id], ['between', 'card_id', $model->card_start, $model->card_end]);
            if ($model->save(false)) {
                return $this->redirectMessage('添加成功', Fun::url(['cardsend/index']));
            }
        }
        return $this->render('create', ['form' => $form->render()]);
    }

    public function actionDetails()
    {
        $id = \Yii::$app->request->get('id');
        if ($id == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model = CardSend::findOne($id);
        $activationCount = CardAttr::find()->where(['status' => 1, 'salesman_id' => $model->salesman_id])->andWhere(['between', 'card_id', $model->card_start, $model->card_end])->count(); //激活数量
        $card_nos = CardAttr::find()->select('card_no')->where(['status' => 1, 'salesman_id' => $model->salesman_id])->andWhere(['between', 'card_id', $model->card_start, $model->card_end])->column();
        $signupCount = Orders::find()->where(['customer_card' => $card_nos, 'pay_status' => [1, 4], 'order_type' => 'appointment'])->count(); //报名数量
        $conversionCount = Orders::find()->where(['customer_card' => $card_nos, 'pay_status' => [1, 4], 'order_type' => 'conversion'])->count(); //转化数量
        $renewCount = Orders::find()->where(['customer_card' => $card_nos, 'pay_status' => [1, 4], 'order_type' => 'renew'])->count(); //续费数量
        $data = [
            'activationCount' => $activationCount,
            'signupCount' => $signupCount,
            'conversionCount' => $conversionCount,
            'renewCount' => $renewCount,
        ];
        $reModel = CardReSend::find()->where(['card_send_id' => $id])->all();
        $reSendData = [];
        if ($reModel != null) {
            foreach ($reModel as $row) {
                $rows['id'] = $row->id;
                $rows['salesman'] = $row->salesman;
                $rows['number'] = $row->number;
                $rows['activationCount'] = CardAttr::find()->where(['status' => 1, 'salesman_id' => $model->salesman_id])->andWhere(['between', 'card_id', $row->card_start, $row->card_end])->count(); //激活数量
                $recard_nos = CardAttr::find()->select('card_no')->where(['status' => 1, 'salesman_id' => $model->salesman_id])->andWhere(['between', 'card_id', $row->card_start, $row->card_end])->column(); //激活数量
                $rows['signupCount'] = Orders::find()->where(['customer_card' => $recard_nos, 'pay_status' => [1, 4], 'order_type' => 'appointment'])->count(); //报名数量
                $rows['conversionCount'] = Orders::find()->where(['customer_card' => $recard_nos, 'pay_status' => [1, 4], 'order_type' => 'conversion'])->count(); //转化数量
                $rows['renewCount'] = Orders::find()->where(['customer_card' => $recard_nos, 'pay_status' => [1, 4], 'order_type' => 'renew'])->count(); //续费数量

                $reSendData[] = $rows;
            }
        }
        return $this->render('details', ['model' => $model, 'reSendData' => $reSendData, 'data' => $data]);
    }

    public function actionView()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        $type = \Yii::$app->request->get('types');
        $id = \Yii::$app->request->get('id');
        if ($type == 'send') {
            $model = CardSend::findOne($id);
            $start = $model->card_start;
            $end = $model->card_end;
            $salesman_id = $model->salesman_id;

        } else {
            $models = CardReSend::findOne($id);
            $model = CardSend::findOne($models->card_send_id);
            $start = $models->card_start;
            $end = $models->card_end;
            $salesman_id = $model->salesman_id;
        }
        $data = [];
        $cardModel = CardAttr::find()->where(['salesman_id' => $salesman_id])->andWhere(['between', 'card_id', $start, $end])->all();
        if ($cardModel != null) {
            foreach ($cardModel as $card) {
                $row['card_no'] = $card->card_no;
                $row['v_code'] = $card->v_code;
                $row['status_name'] = $card->status == 1 ? '已激活' : '未激活';
                $row['name'] = isset($card->customer->name) ? $card->customer->name : '--';

                $data[] = $row;
            }
        }
        return $this->render('view', ['data' => $data]);
    }
}